import {
  CallHandler,
  ExecutionContext,
  Inject,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
export class AuthInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest();
    return next.handle().pipe(
      map((data) => {
        if (!('status' in data)) {
          data.userInfo['id'] =
            request.body.typeNumber === 2
              ? data.userInfo.userInForm.id
              : request.body.typeNumber === 0
              ? data.userInfo.userInForm.sid
              : data.userInfo.userInForm.t_name;

          data.userInfo['name'] =
            request.body.typeNumber === 2
              ? data.userInfo.userInForm.name
              : request.body.typeNumber === 0
              ? data.userInfo.userInForm.s_name
              : data.userInfo.userInForm.t_name;

          if ('userInForm' in data) {
            delete data.userInForm;
          }
        }
        return data;
      }),
    );
    // return next.handle();
  }
}
